/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.base.impl;

import java.io.File;

import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;

import com.cqcis.uip.base.framework.FrameworkConstants;
import com.cqcis.uip.base.framework.common.Role;
import com.cqcis.uip.base.framework.core.RegisteredServiceContext;
import com.cqcis.uip.base.framework.core.ServiceRole;
import com.cqcis.uip.base.framework.core.ServletContainer;
import com.cqcis.uip.base.framework.core.impl.ServletContainerServer.URLRegister;

/**
 * Webapp
 * 
 * @author huangmy
 * @date 2009-4-2
 */
public class DefaultWebAppExporter extends DefaultHttpInvokerExporter {
	private RegisteredServiceContext serviceContext;
	
	@Override
	public void start(RegisteredServiceContext serviceContext) throws Exception {
		// 先删除WAR包释放路径下的内容
		deleteExtraPath();
		this.serviceContext = serviceContext;
		super.start(serviceContext);
	}
	
	@Override
	public void stop(RegisteredServiceContext serviceContext) throws Exception {
		super.stop(serviceContext);
		
		// 删除WAR包释放路径下的内容
		deleteExtraPath();
	}
	
	@Override
	protected HttpInvokerServiceExporter getServiceExporter(
			boolean invokelog,
			Object serviceTarget, Class<?> serviceClazz,
			RegisteredServiceContext serviceContext) {
		return null;
	}
	
	/**
	 * 将自身WAR注册成为Context
	 */
	@Override
	protected URLRegister registerContextURL(ServletContainer server) throws Exception {
		// 获取WAR路径
		String war = this.serviceContext.getBundleContext().getBundle().getLocation();
		return server.registerWAR(getContextPath(), war);
	}
	
	/**
	 * 删除指定file下的所有文件
	 * 
	 * @param file
	 */
	private void deleteAllSubFiles(File file) {
		if (file == null) {
			return;
		}
		if (file.exists()) {
			// 删除文件下面的所有内容
			if (file.isDirectory()) {
				File[] subfiles = file.listFiles();
				if (subfiles != null && subfiles.length > 0) {
					for (File sub : subfiles) {
						deleteAllSubFiles(sub);
					}
				}
			}
			
			file.delete();
		}
	}
	
	private void deleteExtraPath() {
		File file = new File(getExtraTempPath());
		deleteAllSubFiles(file);
	}
	
	/**
	 * WAR 包释放路径
	 * 
	 * @return
	 */
	private String getExtraTempPath() {
		return FrameworkConstants.WEBAPP_EXTRA_PATH + getContextPath();
	}
	
	@ServiceRole(Role.WEBAPP)
	public void setHttpInvokerExportServiceTarget(Object serviceTarget) {
		super.setHttpInvokerExportServiceTarget(serviceTarget);
	}
	
	public Role getRole() {		
		return Role.WEBAPP;
	}
}
